package providers

import (
	"context"
	"time"

	"github.com/asim/go-micro/v3/logger"
	"github.com/asim/go-micro/v3/web"
	"github.com/gin-gonic/gin"
	"github.com/micro/cli/v2"
	"go.uber.org/fx"
)

func NewMicroWebService() (web.Service, *cli.Context) {
	service := web.NewService(
		web.RegisterTTL(time.Minute),
		web.RegisterInterval(time.Second*30),
	)
	var cc *cli.Context
	if err := service.Init(
		web.Action(func(c *cli.Context) {
			serviceName := c.String("service_name")
			logger.Logf(logger.DebugLevel, "service.Init: %s", serviceName)
			cc = c
		}),
	); err != nil {
		logger.Fatal(logger.FatalLevel, err)
	}

	return service, cc
}

func StartMicroWebService(lifecycle fx.Lifecycle, service web.Service, gin *gin.Engine) {
	service.Handle("/", gin)
	lifecycle.Append(fx.Hook{
		OnStart: func(context.Context) error {
			logger.Logf(logger.DebugLevel, "lifecycle.OnStart")
			return service.Run()
		},
	})
}
